package com.acme.bankapp.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class BankClient {

    Socket requestSocket;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    BufferedReader stdIn;

    BankClient() {
    }

    void run() {
	try {
	    requestSocket = new Socket("localhost", 2004);
	    System.out.println("Connected to localhost in port 2004");
	    out = new ObjectOutputStream(requestSocket.getOutputStream());
	    out.flush();
	    in = new ObjectInputStream(requestSocket.getInputStream());
	    stdIn = new BufferedReader(new InputStreamReader(System.in));
	    String userInput;
	    do {
		try {
		    message = (String) in.readObject();
		    System.out.println("server>" + message);
		    
		    while ((userInput = stdIn.readLine()) != null) {
			sendMessage(userInput);
			message = (String) in.readObject();
			System.out.println(message);
			if (message.equals("bye")) {
			    break;
			}
		    }
		} catch (ClassNotFoundException classNot) {
		    System.err.println("data received in unknown format");
		}
	    } while (!message.equals("bye"));
	} catch (UnknownHostException unknownHost) {
	    System.err.println("You are trying to connect to an unknown host!");
	} catch (IOException ioException) {
	    ioException.printStackTrace();
	} finally {
	    try {
		in.close();
		out.close();
		stdIn.close();
		requestSocket.close();
	    } catch (IOException ioException) {
		ioException.printStackTrace();
	    }
	}
    }

    void sendMessage(final String msg) {
	try {
	    out.writeObject(msg);
	    out.flush();
	    System.out.println("client>" + msg);
	} catch (IOException ioException) {
	    ioException.printStackTrace();
	}
    }

    public static void main(final String args[]) {
	BankClient client = new BankClient();
	client.run();
    }

}
